package com.glela.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.glela.common.util.DateUtil;
import com.glela.constant.BizConstant;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.mapper.ChangeProcessLogMapper;
import com.glela.platform.model.ChangeProcessLog;
import com.glela.platform.model.PromotionDetail;
import com.glela.platform.model.PromotionLog;
import com.glela.platform.model.RedeemCode;
import com.glela.platform.model.RedeemCodeLog;
import com.glela.platform.model.User;
import com.glela.platform.model.UserJournal;
import com.glela.platform.model.UserPromotion;
import com.glela.platform.model.request.RequestUserModel;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.service.RedeemCodeService;
import com.glela.platform.service.UserJournalService;
import com.glela.platform.service.UserService;
import com.glela.platform.util.ParameterUtils;
import com.glela.talent.service.TalentService;

/**
 * 兑换码相关
 * 
 * @author 卫耀华
 * @date 2016-10-05 18:18:12
 *
 */
@Controller
@RequestMapping(value = "/redeemCode")
public class RedeemCodeController {

	private static Logger logger = LoggerFactory.getLogger(RedeemCodeController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private RedeemCodeService redeemCodeService;
	@Autowired
	private UserJournalService userJournalService;
	@Autowired
	private TalentService talentService;
	@Autowired
	private ChangeProcessLogMapper LogMapper;

	/**
	 * 使用兑换码
	 * 
	 * @author 卫耀华
	 * @date 2016-10-05
	 * @param userModel
	 * @return
	 */
	@RequestMapping(value = "/useRedeemCode", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> useRedeemCode(@RequestBody RequestUserModel request) {
		logger.info("进入使用兑换码接口");
		try {
			if (ParameterUtils.validParams(request.getRedeemCode(), request.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			// 1、判断用户是否存在
			User user = userService.getUser(request.getUserId());
			if (user == null) {
				// 此用户不存在
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			// 2、查询兑换码信息
			RedeemCode redeemCode = redeemCodeService.selectRedeemCodeByRedeemCode(request.getRedeemCode());
			if (null == redeemCode) {
				// 无此兑换码
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30100), HttpStatus.OK);
			}
			// 3、校验该兑换码的使用次数(可用次数小于等于已用次数则不能使用)
			if ((redeemCode.getUsableTimes() - redeemCode.getUsedTimes()) == 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30101), HttpStatus.OK);
			}
			// 4、查询用户是否已使用过这个兑换码
			RedeemCodeLog useLog = redeemCodeService.selectRedeemCodeLogByRedeemCodeIdAndUserId(redeemCode.getId(),
					request.getUserId());
			if (useLog != null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30102), HttpStatus.OK);
			}
			// 5、判断兑换码的有效时间
			int betweenDate = DateUtil.betweenTime(redeemCode.getStartDate(), redeemCode.getEndDate());
			if (betweenDate == 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30103), HttpStatus.OK);
			}
			// 6、获取优惠券详情
			List<PromotionDetail> detailList = redeemCodeService
					.selectPromotionDetailByPromotionId(redeemCode.getPromotionId());
			if (detailList == null || detailList.size() == 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C30104), HttpStatus.OK);
			}
			for (PromotionDetail detail : detailList) {
				// 判断优惠券的有效时间
				int detailbetweenDate = DateUtil.betweenTime(detail.getEffectiveTime(), detail.getExpirationTime());
				if (detailbetweenDate == 0) {
					continue;// 当前优惠券已过期 进行下一次判断
				}
				// 判断当前用户是否拥有
				UserPromotion userPromotion = redeemCodeService
						.selectUserPromotionByPromotionDetailIdAndUserId(detail.getId(), user.getId());
				if (null == userPromotion) {
					// 校妆的优惠券的类型有：1.现金币 2.通用券 3.品牌券 4.预售券 5.商品券 6 达人激活码
					if (detail.getType() == 6) {
						logger.info("优惠券类型是：达人激活码");
						// 如果输入的码的类型是达人升级码，用户身份直接升级为达人身份
						talentService.activationTalentByRedeemCode(user.getId(), request.getRedeemCode());
					} else if (detail.getType() == 1) {
						// type=1是妆币
						int money = user.getMoney() + detail.getAmount();
						//开始记录日志
						ChangeProcessLog Log=new ChangeProcessLog();
						Log.setDescription("优惠券类型是妆币");
						Log.setMethod("RedeemCodeController.useRedeemCode");
						Log.setPrimaryID(String.valueOf(user.getId()));
						Log.setTableName("yg_user.c_user");
						Log.getBeforeMap().put("Money", user.getMoney());
						Log.getAfterMap().put("Money",money);
						LogMapper.insert(Log);
						//更新账户余额
						userService.updateUserInfonickMoneyById(user.getId(), money);
						// 添加流水账
						UserJournal userJournal = new UserJournal();
						userJournal.setType(BizConstant.TRANS_TYPE_PLUS);// +代表收入
						userJournal.setUserId(user.getId());
						userJournal.setMoney(detail.getAmount());
						userJournal.setPromotionDetailId(detail.getId());
						userJournal.setComment("使用兑换码获得妆币");
						userJournal.setStatus(BizConstant.USER_JOURNAL_STATUS_10);// 使用兑换码获得妆币
						userJournalService.insertUserJournal(userJournal);
						// 添加现金券类型优惠券 领取日志
						PromotionLog promotionLog = new PromotionLog();
						promotionLog.setPromotionDetailId(detail.getId());
						promotionLog.setUserId(user.getId());
						promotionLog.setDrawChannel(BizConstant.PROMOTION_CHANNEL_1);
						redeemCodeService.insertPromotionLog(promotionLog.getPromotionDetailId(),
								promotionLog.getUserId(), promotionLog.getDrawChannel());
					} else {// 2.通用券 3.品牌券 4.预售券 5.商品券,将这些券和用户做个绑定就好
						userJournalService.insertUserPromotion(detail.getPromotionId(), detail.getId(),
								detail.getType(), detail.getPromotionDetailName(), user.getId(), detail.getBrandId(),
								detail.getGoodId(), detail.getLimited(), detail.getIsDiscount(), detail.getAmount(),
								detail.getDiscount(), detail.getEffectiveTime(), detail.getExpirationTime(), 1,detail.getTargetSelfType());
						// 添加优惠券领取日志
						redeemCodeService.insertPromotionLog(detail.getId(), user.getId(),
								BizConstant.PROMOTION_CHANNEL_1);
					}
				} else {
					// 优惠券是否只能使用一次，0是否，1是是，否的话，一个人可以拥有多张相同的优惠券，是的话，相同的优惠券每个人只能拥有一张
					if (detail.getIsOne() == 0) {
						// 相同优惠券，持有数量加1
						userJournalService.updateUserPromotionNumber(userPromotion.getId());
						// 添加优惠劵领取记录
						redeemCodeService.insertPromotionLog(detail.getId(), user.getId(),
								BizConstant.PROMOTION_CHANNEL_1);
					}
				}
			}
			// 更新兑换码使用次数
			redeemCodeService.updateRedeemCodeUsedTimesById(redeemCode.getId(), redeemCode.getUsedTimes() + 1);
			// 记录用户使用兑换码记录
			redeemCodeService.insertRedeemCodeLog(redeemCode.getId(), user.getId());
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("使用兑换码发生异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
}
